#include "iBe.h"

ResourceManagerPtr ResourceManager::inst;

ResourceManager::ResourceManager()
{
  database.open("data/mesh.db");
}

ResourceManager::~ResourceManager()
{}

ResourceManagerPtr ResourceManager::instance()
{
  if ( !inst )
    {
      inst.reset( new ResourceManager() );
    }
  return inst;
}

GLMeshPtr ResourceManager::getMesh(const String &_name)
{
  Handle h;

  h = meshes.getHandle(_name);

  if (h.isInvalid())
    {
      GLMeshPtr retGLMesh;

      retGLMesh = MeshLoader::loadFromDatabase2(database, _name);

      if (retGLMesh)
	{
	  meshes.insert(retGLMesh);
	}

      return retGLMesh;
    }
  else
    {
      return meshes.get(h);
    }
}

/*
ObjectPtr ResourceManager::getObject(const String &_objName, const String &_meshName)
{
  GLMeshPtr mesh;
  ObjectPtr ret;

  mesh = getMesh(_meshName);

  if (mesh)
    {
      ret.reset( new Object() );
      ret->setName( _objName );
      ret->setMesh( mesh );
      ret->setLocation( 0, 0, 0 );
    }
  
  return ret;
}
*/

ObjectPtr ResourceManager::getObject(const String &_objName)
{
  ObjectPtr ret;
  GLMeshPtr mesh;

  ret = MeshLoader::loadObjectFromDatabase( database, _objName );

  if (!ret)
    {
      return ret;
    }

  mesh = getMesh ( ret->getMeshName() );

  if (!mesh)
    {
      ret.reset();
    }

  ret->setMesh( mesh );

 return ret;
}
